import json
from rest_framework.response import Response
from rest_framework.views import APIView

from auto_dj_test import redis_connect
from aweiuser.common import response
from django.contrib.auth.hashers import make_password, check_password
from aweiuser import models, serializers
from django.contrib.auth import get_user_model
from aweiuser.common.token import creat_token
from drf_yasg.utils import swagger_auto_schema

# Create your views here.
# class UserAdmin(BaseUserAdmin):

# 获取用户模型
User = get_user_model()


class RegisterView(APIView):
    """
        注册:{
        "user": "awei"
        "password": "520"
        "email": "20@qq.com"
    }
    :param username:
    :param password:
    :param email:
    :return:
    """
    authentication_classes = ()
    permission_classes = ()

    @swagger_auto_schema(request_body=serializers.UserInfoSerializer)
    def post(self, request):
        try:
            username = request.data["username"]
            password = request.data["password"]
            email = request.data["email"]
        except KeyError:
            return Response(response.KEY_MISS)

        if models.MyUser.objects.filter(username=username).first():
            return Response(response.REGISTER_USERNAME_EXIST)
        if models.MyUser.objects.filter(email=email).first():
            return Response(response.REGISTER_USERNAME_EXIST)
        # 在正常的请求/响应周期中访问时，QueryDicts request.POST和request.GET将是不可变的。要获得可变版本，您需要使用QueryDict.copy().
        # request.data['password']=make_password(password)
        data = request.data.copy()
        data['password'] = make_password(password)
        serializer = serializers.UserInfoSerializer(data=data)  # 序列化数据
        # 并检验数据合法性
        if serializer.is_valid():
            serializer.save()
            return Response(response.REGISTER_SUCCESS)
        else:
            response.KEY_MISS['errors'] = serializer.errors
            return Response(response.KEY_MISS)


class LoginView(APIView):
    """
    登录视图
    authentication_classes 和 permission_classes:
    这两个属性被设置为一个空元组 ()，表示此视图不需要身份验证和权限检查。这意味着即使未经身份验证的用户也可以访问此视图
    """
    authentication_classes = ()
    permission_classes = ()

    def post(self, request):
        try:
            username = request.data['username']
            password = request.data['password']
        except KeyError:
            return Response(response.KEY_MISS)

        user = User.objects.filter(username=username).first()
        if not user:
            return Response(response.USER_NOT_EXISTS)

        if user.is_active == 0:
            return Response(response.USER_BLOCKED)

        if not check_password(password, user.password):
            return Response(response.LOGIN_FAILED)

        # 生成token并返回
        token = creat_token(user)
        user_ser = serializers.UserModelSerializer(instance=user)  # 序列化数据方便转json存储进redis
        redis_connect.set(token, json.dumps(user_ser.data), 86400)  # 24*60*60  一天
        response.LOGIN_SUCCESS['token'] = token
        response.LOGIN_SUCCESS['user'] = user.username
        response.LOGIN_SUCCESS['is_superuser'] = user.is_superuser
        return Response(response.LOGIN_SUCCESS)


class UserView(APIView):
    authentication_classes = ()
    permission_classes = ()

    def get(self, request):
        # users = models.MyUser.objects.filter(id=request.data['id'])
        users = User.objects.filter(is_active=1)
        if not users:
            return Response(response.USER_NOT_EXISTS)
        ser = serializers.UserListModelSerializer(instance=users, many=True)
        return Response(ser.data)
